package com.eh.erd.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.eh.erd.core.mapper.DictMapper;
import com.eh.erd.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuyuanwei
 * @version 1.0
 * @date 2021/5/7 16:50
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    List<ExcelDictDTO> list=new ArrayList<ExcelDictDTO>();

    static final int BATCH_COUNT=5;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext analysisContext) {
        log.info("解析一条记录：{}",data);
        list.add(data);
        if(list.size()>=BATCH_COUNT){
            saveData();
            list.clear();
        }
    }

    private void saveData() {
            //批量保存
        dictMapper.insertBatch(list);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //收尾  当不足五条时保存
        saveData();
    }
}
